clear
set more off

cap log close
log using "$logdir/preparers.log", replace

use $fromsasdir/result if num_emp > 0 & wg_amt/num_emp > 20 & tp == 202103 & naics3 == "722", clear

gen byte any_ertc = ertc > 0
gen byte any_amendment = ertc_amendment > 0
gen either = any_ertc | any_amendment
sum any_ertc any_amendment either
// egen snum = group(st)
destring naics6, replace force

destring zip, replace force


*************************************************
*	Better preparer counterfactual		*
*************************************************

//bys prep_id: gegen n = count(tin)
foreach var in any_ertc any_amendment either {
    preserve
    qui reghdfe `var' , a(fehat = prep_id bhat2 = bin#zip#naics6)
    local cons = _b[_cons]
    drop if missing(fehat)

    gen fit = `cons' + fehat + bhat2
    sum fit 
    sum `var'
    local b0 = r(mean)

    sum fehat, detail

    qui _pctile fehat if prep_id > 0, p(50)
    gen fit_cf50 = `cons' + max(fehat, r(r1)) + bhat2
    sum fit_cf50
    local b50 = r(mean)

    qui _pctile fehat if prep_id > 0 , p(75)
    gen fit_cf75 = `cons' + max(fehat, r(r1)) + bhat2
    sum fit_cf75
    local b75 = r(mean)

    qui _pctile fehat if prep_id > 0 , p(90)
    gen fit_cf90 = `cons' + max(fehat, r(r1)) + bhat2
    sum fit_cf90
    local b90 = r(mean)
    
    gcollapse (firstnm) fehat_`var' = fehat, by(prep_id) fast
    tempfile fes_`var'
    qui save `fes_`var'', replace
    

    
    clear
    qui set obs 1
    foreach k in 0 50 75 90 {
        qui gen b`k' = `b`k''
    }
    gen var = "`var'"
    tempfile d`var'
    qui save `d`var'', replace
    restore
}

use `fes_any_ertc', clear
merge 1:1 prep_id using `fes_any_amendment', nogen
corr fehat_any_ertc fehat_any_amendment



clear
foreach var in any_ertc any_amendment either {
    append using `d`var''
}
qui save $outdir/preparers, replace
list



cap log close

